package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.LoginRespEntity;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Controller
@RequestMapping("/oauth2.0")
@SuppressWarnings("all")
public class Oath2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/logout")
    public String login(HttpSession session) {
        if (session.getAttribute("loginUser") != null) {//只是为了防止空指针
            log.info("\n[" + ((LoginRespEntity) session.getAttribute("loginUser")).getUsername() + "] 已下线");
        }
        session.invalidate();
        return "redirect:http://auth.gulimall.com/login.html";
    }

    /**
     * 登录成功回调
     * {
     * "access_token": "2.00snwAOGOmJAkBcc03bd161bXVD78C",
     * "remind_in": "157679999",
     * "expires_in": 157679999,
     * "uid": "5703891740",
     * "isRealName": "true"
     * }
     * 汀西氟的我是你	---		2.00snwAOGOmJAkBcc03bd161bXVD78C
     */
    /**
     * 第三方微博登录获取token
     * RequestParam和@PathVariable这两者之间区别不大，主要是请求的URL不一样
     * 用@RequestParam请求接口时,URL是:http://www.test.com/user/getUserById?userId=1
     * 用@PathVariable请求接口时,URL是:http://www.test.com/user/getUserById/2
     */
    @RequestMapping("/weibo/success")
    public String getAccessToken(@RequestParam("code") String code, HttpSession session) throws Exception {
        //首先拿着code去请求这个地址：https://api.weibo.com/oauth2/access_token
        Map<String, String> querys = new HashMap<>();
        querys.put("client_id", "3021246486");
        querys.put("client_secret", "3b506da5494bfe1966ebbea1eef46e7e");
        querys.put("grant_type", "authorization_code");
        querys.put("code", code);
        querys.put("redirect_uri", "http://auth.gulimall.com/weibo/success");
        Map<String, String> headers = new HashMap<>();
        HttpResponse response = HttpUtils.doPost("http://api.weibo.com", "/oauth2/access_token", "post", headers, null, querys);
        //处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了AccessToken
            //EntityUtils是apache提供的实体工具类
            HttpEntity entity = response.getEntity();
            System.out.println("entity:===============" + entity);
            String json = EntityUtils.toString(response.getEntity());
            System.out.println("json:=================" + json);
            //response.getEntity()得到的就是下面的JSON
            //{
            //    "access_token": "2.00HLWpRGCOq9SD28c0970b3bZlBGuD",
            //    "remind_in": "157679999",
            //    "expires_in": 157679999,
            //    "uid": "5760273129",
            //    "isRealName": "true"
            //}

            //将json字符串转成我们想要的对象
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            String accessToken = socialUser.getAccessToken();

            // 相当于我们知道了当前是那个用户
            // 1.如果用户是第一次进来 自动注册进来(为当前社交用户生成一个会员信息 以后这个账户就会关联这个账号)
            R login = memberFeignService.login(socialUser);
            if (login.getCode() == 0) {
                LoginRespEntity rsepVo = login.getData("data", new TypeReference<LoginRespEntity>() {
                });

                log.info("\n欢迎 [" + rsepVo.getUsername() + "] 使用社交账号登录");
                // 第一次使用session 命令浏览器保存这个用户信息 JESSIONSEID 每次只要访问这个网站就会带上这个cookie
                // 在发卡的时候扩大session作用域 (指定域名为父域名)
                // TODO 1.默认发的当前域的session (需要解决子域session共享问题)
                // TODO 2.使用JSON的方式序列化到redis
//				new Cookie("JSESSIONID","").setDomain("kkmall.com");
                session.setAttribute("loginUser", rsepVo);
                // 登录成功 跳回首页
                return "redirect:http://gulimall.com";
            } else {
                //获取token失败就跳转到登录页
                return "redirect:http://auth.gulimall.com/login.html";
            }
            //登录成功跳转到首页
        }
        return "redirect:http://gulimall.com";
    }
}
